import { defineStore } from 'pinia'
import { getToken,getName, setToken,setName, removeToken } from '../../utils/auth'
import {store} from '../index'
import type { LoginInput ,LoginResponse} from '@/types/login'
import {Create } from '@/api/login'
import { ref } from 'vue'


export const useUserStore = defineStore('user',()=>{
  var token = getToken()
  var name = getName()
  const user_token = ref('')
  const user_name = ref('')
  user_token.value = token
  user_name.value = name
  const SET_TOKEN = (token: string) => {
    setToken(token)
  }
  const SET_NAME = (name: string) => {
    setName(name)
  }
  const login = (userInfo: LoginInput) => {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      Create({ username: username.trim(), password: password }).then((response:LoginResponse) => {
        console.log('store user.js login response:',response)
        const { data } = response
        SET_TOKEN(data.token)
        SET_NAME(data.name)
        console.log('store login resolve before',data.name)
        resolve
        console.log('store login resolve after')
      }).catch(error => {
        reject(error)
      })
    })
  }
  const logout = () => {
      removeToken()
  }
  const removeToken = () => {
    RESET_STATE()
  }
  const RESET_STATE = () => {
    user_token.value = ''
    user_name.value = ''
  }
  return {user_name, user_token,  login, logout}
})


// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store)
}
